package net.bxx2004.extand.events;

import net.bxx2004.extand.extand;
import net.bxx2004.extand.manager.ConfigManager;
import net.bxx2004.extand.util.CodeCreate;
import net.bxx2004.extand.util.JDBCUtil;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class PlayerJoin implements Listener {
    private Player player;
    @EventHandler
    public void onJoin(PlayerJoinEvent event){
        this.player = event.getPlayer();
        switch (ConfigManager.getSetting().getString("Storge.Type")){
            case "Yaml":
                a();
                break;
            case "MySql":
                try {
                    String sql = "SELECT PlayerName FROM " + ConfigManager.getSetting().getString("Storge.SqlTablename");
                    Connection conn = JDBCUtil.getConnection();
                    Statement st = conn.createStatement();
                    ResultSet resultSet = st.executeQuery(sql);
                    List<String> names = new ArrayList<>();
                    while (resultSet.next()){
                        names.add(resultSet.getString(1));
                    }
                    if (!names.contains(player.getName())){
                        String sql1 = "insert into "+ ConfigManager.getSetting().getString("Storge.SqlTablename") +"(PlayerName,BackPlayer,Code,Amount) values(?,?,?,?)";
                        PreparedStatement ps = conn.prepareStatement(sql1);
                        ps.setString(1, player.getName());
                        ps.setString(2, "no");
                        ps.setString(3, CodeCreate.getCode());
                        ps.setInt(4, 0);
                        ps.executeUpdate();
                        ps.close();
                    }
                    JDBCUtil.close(resultSet, st, conn, null);
                }catch (Exception e){
                    System.out.println("[Extand] -> MySql添加或查询数据失败...");
                    e.printStackTrace();
                }
                break;
            default:
                a();
                break;
        }

    }
    public void a(){
        Iterator iterator = ConfigManager.getConfig().getKeys(false).iterator();
        List<String> names = new ArrayList<String>();
        while (iterator.hasNext()){
            String Name = (String) iterator.next();
            names.add(Name);
        }
        if (!names.contains(player.getName())){
            ConfigManager.getConfig().set(player.getName() + ".Code", CodeCreate.getCode());
            ConfigManager.getConfig().set(player.getPlayer().getName() + ".Amount", 0);
            ConfigManager.getConfig().set(player.getPlayer().getName() + ".BackPlayer", "无");
            extand.getPlugin(extand.class).saveConfig();
        }
    }
}
